package com.gudy.counter.Controller;

import com.gudy.counter.bean.Account;
import com.gudy.counter.bean.CaptchaRes;
import com.gudy.counter.bean.CounterRes;
import com.gudy.counter.cache.RedisStringCache;
import com.gudy.counter.enumutil.CacheType;
import com.gudy.counter.service.AccountSerivce;
import com.gudy.counter.thirdpaet.uuid.GudyUuid;
import com.gudy.counter.util.Captcha;
import com.gudy.counter.util.ConstCommon;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/login")
@Log4j2
public class LoginController {

    @Autowired
    RedisStringCache redisStringCache;

    @Autowired
    AccountSerivce accountSerivce;

    @RequestMapping("/captcha")
    public CounterRes capecha() throws IOException {
        //1.生成验证码 120长，高40，4个字符，藻条+线条
        Captcha captcha = new Captcha(120, 40, 4, 10);

        //2.把验证码放入缓存ID 验证码数值
        //生成随机的uuid确保不会重复
        String uuid = String.valueOf(GudyUuid.getInstance().getUUID());
        RedisStringCache.saveCache(uuid,captcha.getCode(), CacheType.CAPTCHA);
        //3.base64编码图片返回前台
        //uuid base64
        CaptchaRes captchaRes = new CaptchaRes();
        captchaRes.setId(uuid);
        captchaRes.setImageBase64(captcha.getBasee64ByteStr());
        return new CounterRes(captchaRes);
    }
    @RequestMapping("/userlogin")
    public CounterRes userlogin(@RequestParam long uid , @RequestParam String password,@RequestParam String captcha,@RequestParam String captchaId) throws Exception {
        Account login = accountSerivce.login(uid, password, captcha, captchaId);
        if (login != null){
            return  new CounterRes(login);
        }
        return new CounterRes(ConstCommon.RELOGIN,"用户名密码/验证码错误",null);
    }

    @RequestMapping("/loginfaile")
    public CounterRes loginFaile(){
        return new CounterRes(ConstCommon.RELOGIN,"请重新登录",null);
    }

    @RequestMapping("/logout")
    public CounterRes logout(@RequestParam String token){
        accountSerivce.logout(token);
        return new CounterRes(ConstCommon.SUCCESS,"退出成功",null);
    }

    @RequestMapping("updatePassword")
    public  CounterRes updatePassword(@RequestParam long uid,@RequestParam String oldpassword,@RequestParam String newpassword){
        return accountSerivce.updatePassword(uid,oldpassword,newpassword);
    }
}
